<?php
header('Content-Type: application/json');

$user = isset($_COOKIE['enorg']) ? $_COOKIE['enorg'] : 'bozo'; 

// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '只支持POST请求']);
    exit;
}

// 获取POST数据
$data = json_decode(file_get_contents('php://input'), true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => '无效的数据格式']);
    exit;
}

$type = $data['type'] ?? '';
$title = $data['title'] ?? '';
$category = $data['category'] ?? '';
$password = $data['password'] ?? '';

// 验证必要字段
if (empty($type) || empty($title)) {
    echo json_encode(['success' => false, 'message' => '缺少必要字段']);
    exit;
}

// 验证密码
if ($password !== 'Delete') {
    echo json_encode(['success' => false, 'message' => '密码错误']);
    exit;
}

try {
    if ($type === 'file') {
        // 删除文件
        $dir = '';
        switch ($category) {
            case 'geo':
                $dir = '../'.$user.'-output/GEO';
                break;
            case 'agent':
                $dir = './AGENT';
                break;
            case 'system':
                $dir = './SYSTEM';
                break;
            default:
                echo json_encode(['success' => false, 'message' => '无效的分类']);
                exit;
        }
        
        // 构建文件路径
        $filename = $dir . '/' . $title . '.txt';
        
        // 检查文件是否存在
        if (!file_exists($filename)) {
            echo json_encode(['success' => false, 'message' => '文件不存在']);
            exit;
        }
        
        // 删除文件
        if (unlink($filename)) {
            echo json_encode(['success' => true, 'message' => '文件删除成功']);
        } else {
            echo json_encode(['success' => false, 'message' => '文件删除失败']);
        }
    } elseif ($type === 'json') {
        // 删除JSON数据
        $jsonFile = './'.$user.'.json';
        
        // 读取现有数据
        if (!file_exists($jsonFile)) {
            echo json_encode(['success' => false, 'message' => 'JSON文件不存在']);
            exit;
        }
        
        $jsonData = json_decode(file_get_contents($jsonFile), true);
        
        // 检查键是否存在
        if (!isset($jsonData[$title])) {
            echo json_encode(['success' => false, 'message' => '数据项不存在']);
            exit;
        }
        
        // 删除数据
        unset($jsonData[$title]);
        
        // 保存文件
        if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
            echo json_encode(['success' => true, 'message' => '用户提示词删除成功']);
        } else {
            echo json_encode(['success' => false, 'message' => '用户提示词删除失败']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => '无效的类型']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => '删除失败: ' . $e->getMessage()]);
}
?>